//
//  MessageSendViewController.m
//  FVQuickMessage
//
//  Created by HoiChen on 16/8/18.
//  Copyright © 2016年 zty. All rights reserved.
//

#import "MessageSendViewController.h"
#import "Message.h"
#import "ChatTableViewCell.h"


@interface MessageSendViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate,IEMChatProgressDelegate, EMChatManagerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *DataArray;
@property (nonatomic, strong) Message *message;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UITextField *textField;

@property (nonatomic, assign) BOOL result;

@property (nonatomic, strong) UIButton *sendButton;

/**会话数组*/
@property (nonatomic, strong) NSMutableArray *chatArray;

@end

@implementation MessageSendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.chatArray = [NSMutableArray array];
    
    [self handle];
    
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-45-64) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    //    _tableView.rowHeight = 200;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.contentOffset = CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX);
    [self.view addSubview:_tableView];
    
    [_tableView registerClass:[ChatTableViewCell class] forCellReuseIdentifier:@"tableCell"];
    
    
    [self createBttomView];
    //注册键盘出现的通知
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShown:)
     
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    //注册键盘消失的通知
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden:)
     
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    
    // 接收消息
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
}

- (void)handle {
    
    //获取本地聊天信息, 获取当前对象的会话
    EMConversation *conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:self.buddy.username conversationType:eConversationTypeChat];
    
    //加载会话信息

    self.chatArray = (NSMutableArray *)[conversation loadAllMessages];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    // 根据数据
    return _chatArray.count;
}

-(void)createBttomView {
    NSLog(@"1");
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, HEIGHT-45-64, WIDTH, 45)];
    //    imageView.backgroundColor = [UIColor blackColor];
    _imageView.image = [UIImage imageNamed:@"toolbar_bottom_bar"];
    _imageView.userInteractionEnabled = YES;
    [self.view addSubview:_imageView];
    
    // 键盘  语音  切换
    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn1 setImage:[UIImage imageNamed:@"chat_bottom_voice_press"] forState:UIControlStateNormal];
    //[btn1 setImage:[UIImage imageNamed:@"chat_bottom_voice_nor"] forState:UIControlStateHighlighted];
    btn1.frame = CGRectMake(5, 5, 37, 40);
    
    
    UIButton *voice = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn1 setImage:[UIImage imageNamed:@"chat_bottom_voice_nor"] forState:UIControlStateHighlighted];
    voice.frame = CGRectMake(5, 5, 37, 40);
    
    
    [btn1 addTarget:self action:@selector(btn1Aciton) forControlEvents:UIControlEventTouchUpInside];
    [_imageView addSubview:btn1];
    
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(47, 6, WIDTH - 47 - 95, 32)];
    _textField.layer.cornerRadius = 6;
    _textField.tag = 1001;
    _textField.textAlignment = NSTextAlignmentRight;
    _textField.backgroundColor = [UIColor whiteColor];
    _textField.delegate = self;
    [_imageView addSubview:_textField];
    
    // 加号
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn2 setImage:[UIImage imageNamed:@"chat_bottom_up_nor"] forState:UIControlStateNormal];
    [btn2 setImage:[UIImage imageNamed:@"chat_bottom_up_press"] forState:UIControlStateHighlighted];
    btn2.frame = CGRectMake(WIDTH-90, -2, 50, 50);
    [_imageView addSubview:btn2];
    
    // 表情
    UIButton *btn3 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn3 setImage:[UIImage imageNamed:@"chat_bottom_smile_nor"] forState:UIControlStateNormal];
    [btn3 setImage:[UIImage imageNamed:@"chat_bottom_smile_press"] forState:UIControlStateHighlighted];
    btn3.frame = CGRectMake(WIDTH-50, -2, 50, 50);
    [btn3 addTarget:self action:@selector(send) forControlEvents:UIControlEventTouchUpInside];
    [_imageView addSubview:btn3];
    
    
    self.sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.sendButton addTarget:self action:@selector(sendbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_imageView addSubview:_sendButton];
    
}
// 语音
-(void)btn1Aciton {
    
    if (_result) {
        _sendButton.hidden = NO;
        _textField.hidden = YES;
        _sendButton.frame = CGRectMake(47, 6, WIDTH - 47 - 95, 32);
        [_sendButton setTitle:@"长按发送" forState:UIControlStateNormal];
    }else{
        _sendButton.hidden = YES;
        _textField.hidden = NO;
        
    }
    _result = !_result;
    
}

// 笑脸发送
- (void)send {
    
    
}

- (void) sendbuttonAction:(UIButton *)button {
    
    NSLog(@"录制语音");
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ChatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableCell"];
    cell.message = _chatArray[indexPath.row];
    
    return cell;
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ChatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableCell"];
    cell.message = _chatArray[indexPath.row];
    
    return cell.rowHeight;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)keyboardWasShown:(NSNotification*)aNotification {
    
    //键盘高度
    CGRect keyBoardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //    [_tableView setContentOffset:CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX)];
    //表视图滚动至底部。
    [UIView animateWithDuration:0.5 animations:^{
        _tableView.frame = CGRectMake(0, -keyBoardFrame.size.height, WIDTH, HEIGHT-64-45);
        _imageView.frame = CGRectMake(0,  HEIGHT-45-64-keyBoardFrame.size.height, WIDTH, 45);
    }];
    
    
    //重新加载表视图
    //    [_tableView reloadData];
    
    
}

-(void)keyboardWillBeHidden:(NSNotification*)aNotification{
    _imageView.frame = CGRectMake(0, HEIGHT-45-64, WIDTH, 45);
    _tableView.frame = CGRectMake(0, 0, WIDTH, HEIGHT-64-45);
    [_tableView reloadData];
    
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [_tableView setContentOffset:CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX)];
    
    
    
    
    
    NSString *str =  _textField.text;
 _textField.text = @"";
    if (str.length == 0) {
        return NO;
    }else{
        //5.内容对象
        EMChatText *text = [[EMChatText alloc] initWithText:str];
        //4.消息体
        /* EMTextMessageBody; 文本消息体
         EMImageMessagebody 图片消息体
         EMVideoMessageBody 视频消息体
         EMVoiceMessageBody 声音消息体
         */
        EMTextMessageBody *textBody = [[EMTextMessageBody alloc] initWithChatObject:text];
        //3.接受者
        NSString *reciver = self.buddy.username;
        //2.EMMessage对象
        EMMessage *msg = [[EMMessage alloc] initWithReceiver:reciver bodies:@[textBody]];
        //1.发送消息
        
        [[EaseMob sharedInstance].chatManager asyncSendMessage:msg progress:self prepare:^(EMMessage *message, EMError *error) {
            NSLog(@"消息即将发送");
        } onQueue:nil completion:^(EMMessage *message, EMError *error) {
            NSLog(@"消息发送完成");
        } onQueue:nil];
        
        
    }
    /******************************/
    [self handle];
    [self.tableView reloadData];
    
 
    //表视图滚动至底部。
    
    
    //    @"icon"];
    //    _message.content = [_DataArray[indexPath.row] valueForKey:@"content"];
    //    _message.time = [_DataArray[indexPath.row] valueForKey:@"time"];
    //    _message.isSelf = [_DataArray[indexPath.row] valueForKey:@"isSelf"];
    return YES;
}

#pragma mark - 单机窗口键盘隐藏
//说明：其实是选中到单元格了
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //直接调用隐藏键盘的方法即可
    [_textField resignFirstResponder];
}

-(void)setProgress:(float)progress forMessage:(EMMessage *)message forMessageBody:(id<IEMMessageBody>)messageBody{
    
}

#pragma mark - 滑动窗口时，键盘隐藏
- (void) scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    //直接调用隐藏键盘的方法即可
    [_textField resignFirstResponder];
    
}


// 接收消息
-(void)didReceiveMessage:(EMMessage *)message{
    [_chatArray addObject:message];
    [self.tableView reloadData];
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
